package org.ultrapower.checkuser.core.util;

import java.io.*;
import java.util.Iterator;
import java.util.List;

/**
 * Created by zhaopan on 2017/7/6.<br>
 *
 * @Description:
 */
public class FileUtil
{
    //复制文件
    public static void saveFile(File outfile, InputStream inputStream) throws IOException
    {
        //保存文件
        OutputStream outputStream = new FileOutputStream(outfile);
        int length = 0;
        byte[] buf = new byte[1024];
        while ((length = inputStream.read(buf)) != -1)
        {
            outputStream.write(buf, 0, length);
        }
        inputStream.close();
        outputStream.close();
    }

    /**
     * 导出csv
     * @param outFile 输出路径
     * @param datas 数据
     * @param isCover 是否覆盖
     * @return
     */
    public static void exportCsv(File outFile,List<String[]> datas,boolean isCover) throws Exception
    {
        //File csvFile = null;
        BufferedWriter csvFileOutputStream = null;
        String[] propertyEntry = null;
        //String re = null;
        try
        {
            csvFileOutputStream = new BufferedWriter(
                    new OutputStreamWriter(new FileOutputStream(outFile,isCover),
                            "GB2312"));
                for (Iterator propertyIterator = datas.iterator(); propertyIterator
                        .hasNext(); )
                {
                    propertyEntry = (String[]) propertyIterator.next();
                    int tab=1;
                    for(String re:propertyEntry){
                        csvFileOutputStream.write("\"" + re + "\"");
                        if(tab++!=propertyEntry.length)csvFileOutputStream.write(",");
                    }
                    csvFileOutputStream.newLine();
                    csvFileOutputStream.flush();
                }
            csvFileOutputStream.flush();
        } catch (Exception e)
        {
            e.printStackTrace();
            if (outFile.exists())outFile.delete();
            throw new Exception("数据导出错误");
        } finally
        {
            if (csvFileOutputStream != null)csvFileOutputStream.close();
        }
    }
}
